package com.gitee.loyo.interfaces.impl

import com.gitee.loyo.KSQL

class InsertSQL<T: Any>(
    private val obj: T,
    private val tableName: String? = null,
    private val selective: Boolean = true,
    private val columnNameFilter: (String) -> Boolean = { true }
) : BaseModelSQL<T>() {

    init {
        buildSQL()
    }

    override fun buildSQL() {
        builder.append("insert into ")
            .append(tableName?:KSQL.nameMappingStrategy.toColumnName(obj.javaClass.simpleName))
            .append("(")

        var i = 0
        eachFields(obj){ columnName, value ->
            if(selective) {
                if (KSQL.nullDetector.isNull(value))
                    return@eachFields
            }

            if(!columnNameFilter.invoke(columnName))
                return@eachFields

            if(i++ > 0){
                builder.append(", ")
            }
            builder.append(columnName)
            parameters.add(value)
        }
        builder.append(")values(")
        var j = i
        while (j > 0){
            if(j-- < i){
                builder.append(", ")
            }
            builder.append("?")
        }
        builder.append(")")
    }


}